﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using IdentityModel;
using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Traceability.Register.Application.Commonds.LoginCommond;
using Traceability.Register.Domain;
using Traceability.Register.ErrorCode.Result;
using Traceability.Register.Infrastructrue;
using Microsoft.Extensions.Configuration;
namespace Traceability.Register.Application.CommondHandlers.LoginCommondHandlers
{
    /// <summary>
    /// 登录请求命令处理
    /// </summary>
    public class UserLoginCommondHandler : IRequestHandler<UserLoginCommond, ApiResult>
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IBaseRepository<UserInfo> baseRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UserLoginCommondHandler> logger;
        private readonly IConfiguration configuration;
        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        /// <param name="baseRepository">用户仓储</param>
        /// <param name="logger">日志</param>
        public UserLoginCommondHandler(IBaseRepository<UserInfo> baseRepository, ILogger<UserLoginCommondHandler> logger,IConfiguration configuration)
        {
            this.baseRepository = baseRepository;
            this.logger = logger;
            this.configuration = configuration;
        }
        /// <summary>
        /// 登录成功
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回结果</returns>
        public async Task<ApiResult> Handle(UserLoginCommond request, CancellationToken cancellationToken)
        {
            try
            {
                var list = await baseRepository.QueryAsync(x=>x.UserinfoName==request.UserName);
                if (list.Count() == 0)
                {
                    return  ApiResult.Fail("用户名不存在");
                }
                if (list.Where(x => x.Password == request.UserPwd).Count() == 0)
                {
                    return ApiResult.Fail("用户名与密码不匹配");
                }
                var Token = GenerateToken(list.FirstOrDefault()!);
                return ApiResult.Ok(Token);
                
            }
            catch (Exception ex)
            {
                return ApiResult.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 生成jwt token
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        private string GenerateToken(UserInfo admin)
        {
            IList<Claim> claims = new List<Claim> {
                                new Claim(JwtClaimTypes.Id, admin.UserinfoId.ToString()),
                                new Claim(JwtClaimTypes.Name, admin.UserinfoName)
                            };

            //JWT密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:Bearer:SecurityKey"]));

            //算法
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //过期时间
            DateTime expires = DateTime.UtcNow.AddMinutes(30);

            //Payload负载
            var token = new JwtSecurityToken(
                issuer: configuration["JwtConfig:Bearer:Issuer"],
                audience: configuration["JwtConfig:Bearer:Audience"],
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: expires,
                signingCredentials: cred
                );

            var handler = new JwtSecurityTokenHandler();

            //生成令牌
            string jwt = handler.WriteToken(token);

            return jwt;
        }
        //写一个冒泡排序


    }
}
